//
//  ZNWBStatusViewModel.swift
//  ZNWeibo
//
//  Created by FunctionMaker on 2017/8/22.
//  Copyright © 2017年 FunctionMaker. All rights reserved.
//

import Foundation

// 微博视图模型持有微博数据模型
// 遵守CustomStringConvertible协议，以便在没有父类的情况下，定义description输出调试信息

// 表格优化
// 尽量少计算，或者提前计算好，根据滚动设置隐藏
// 不要动态创建控件和使用CornerRadius和混合渲染图层
// Cell的控件越少越好，层次越少越好，要测量不要猜测
class ZNWBStatusViewModel: CustomStringConvertible {
    // 微博模型
    var status: ZNWBStatus
    
    // 会员图标
    var memberIcon: UIImage?
    /// 认证图标
    var vipIcon: UIImage?
    
    /// 转发文字
    var retweetedStr: String?
    /// 评论文字
    var commentStr: String?
    /// 点赞文字
    var likeStr: String?
    
    /// 配图视图大小
    var picturesViewSize = CGSize()
    
    /// 缓存行高
    var cacheRowHeight: CGFloat = 0
    
    /// 被转发的微博正文的属性文字
    var retweetedAttrContent: NSAttributedString?
    /// 微博正文的属性文字
    var statusAttrContent: NSAttributedString?
    
    /// 如果是转发的微博，此原创微博一定没有图
    /// 如果被转发的微博有配图，则返回；否则返回原创微博的配图，
    var picURLs: [ZNWBStatusPicture]? {
        return status.retweeted_status?.pic_urls ?? status.pic_urls
    }
    
    
    init(model: ZNWBStatus) {
        status = model
        
        let mbrank = model.user?.mbrank ?? 0
        
        if mbrank > 0 && mbrank < 7 {
            let imageName = "common_icon_membership_level\(mbrank)"
            
            memberIcon = UIImage(named: imageName)
        }
        
        switch model.user?.verified_type ?? 0 {
        case 0:// 无认证
            vipIcon = UIImage(named: "avatar_vip")
        case 2, 3, 5:
            vipIcon = UIImage(named: "avatar_enterprise_vip")
        case 220:
            vipIcon = UIImage(named: "avatar_grassroot")
        default:
            break
        }
        
        retweetedStr = countString(count: model.reposts_count, defaultStr: "转发")
        commentStr = countString(count: model.comments_count, defaultStr: "评论")
        likeStr = countString(count: model.attitudes_count , defaultStr: "赞")
        
        // 有原创就计算原创，否则就计算被转发
        picturesViewSize = calculatePicViewSize(count: picURLs?.count)
        
        // 拼接原创微博正文内容
        var rText = "@" + (status.retweeted_status?.user?.screen_name ?? "") + ":"
        rText = rText + (status.retweeted_status?.text ?? "")
        
        retweetedAttrContent = ZNEmotionManager.shared.emoticonString(withString: rText, font: ZNWBRetweetedCellContentFont)
        statusAttrContent = ZNEmotionManager.shared.emoticonString(withString: status.text ?? "", font: ZNWBOrigCellContentFont)
        
        calculateCellHeight()
    }
    
    /// 根据单图更新配图视图的大小
    ///
    /// - Parameter image: 网络缓存的单张配图
    func updateSingleImageSize(image: UIImage) {
        var size = image.size
        
        size.height += ZNWBPicturesViewOutterMargin
        
        // 更新缓存行高
        
        // 1. 减去之前的配图视图高
        cacheRowHeight -= picturesViewSize.height
        
        // 2. 加上现在的配图视图高
        cacheRowHeight += size.height
        
        picturesViewSize = size
    }
    
    var description: String {
        return status.description
    }
    
    /// 根据数字返回用于描述转发、评论、点赞字符串
    ///
    /// - Parameters:
    ///   - count: 数字
    ///   - defaultStr: 默认字符串
    /// - Returns: 返回结果
    private func countString(count: Int, defaultStr: String) -> String {
        if count == 0 {
            return defaultStr
        } else if count < 10000 {
            return count.description
        } else {
            return String(format: "%.2f万", Float(count) / 10000)
        }
    }
    
    /// 计算配图视图大小
    ///
    /// - Parameter count: 图片数量
    /// - Returns: 图片大小
    private func calculatePicViewSize(count: Int?) -> CGSize {
        if count == 0 || count == nil {
            return CGSize()
        }
        
        // 计算行数
        /*
            1 2 3 = 0 1 2 / 3 = 0 + 1 = 1
            4 5 6 = 3 4 5 / 3 = 1 + 1 = 2
         */
        let row = CGFloat((count! - 1) / 3 + 1)
        
        // 计算高度
        var height = ZNWBPicturesViewOutterMargin
        height += (row * ZNWBPictureCellWidth)
        height += ((row - 1) * ZNWBPicturesViewInnerMargin)
        
        return CGSize(width: ZNWBPicturesViewWidth, height: height)
    }
    
    private func calculateCellHeight() {
        // 原创微博：顶部分隔视图(12) + 间距(12) + 头像高度(34) + 间距(12) + 正文高度(计算) + 配图视图高度(计算) + 间距(12) + 底部视图高度(35)
        
        // 转发微博：顶部分隔视图(12) + 间距(12) + 头像高度(34) + 间距(12) + 正文高度(计算) + 间距(12) + 间距(12) + 转发微博文本高度(计算) + 配图视图高度(计算) + 间距(12) + 底部视图高度(35)
        var height: CGFloat = 0
        
        height = 2 * ZNWBCellInnerMargin + ZNWBCellIconHeight + ZNWBCellInnerMargin
        
        // 计算正文高度
        // 涉及到换行文字的计算都需要使用.usesLineFragmentOrigin选项
        if let text = statusAttrContent {
            height += text.boundingRect(with: ZNWBCellContentBoundingSize,
                                        options: .usesLineFragmentOrigin,
                                        context: nil).height
        }
        
        // 计算转发文字高度
        if status.retweeted_status != nil {
            height += 2 * ZNWBCellInnerMargin
            height += retweetedAttrContent!.boundingRect(with: ZNWBCellContentBoundingSize,
                                                     options: .usesLineFragmentOrigin,
                                                     context: nil).height
        }
        
        // 累加剩下的高度
        height += picturesViewSize.height + ZNWBCellInnerMargin + ZNWBCellBottomViewHeight
        
        // 设置缓存行高
        cacheRowHeight = height
    }
}
